//
//  KAExitReasonPusher.swift
//  kano
//
//  Created by Frank on 2025/5/15.
//

import UIKit

class KAExitReasonPusher: KAPushView {
    var reasonSelected: ((String, Bool) -> Void)?
    private var selectedSectionModel = KAExitReasonModel()
    private var selectedRowModel = KAExitReasonModel()
    
    var dataArray: [KAExitReasonModel] = [] {
        didSet {
            var_tableView.reloadData()
        }
    }
    
    lazy var var_tableView: UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0,
                                                  y: kscale(50),
                                                  width: UIScreen.main.bounds.width,
                                                  height: var_shadowView.height - kscale(150) - UIDevice.ka_safeBottom), style: .grouped)
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        tableView.register(KAExitReasonHeader.self, forHeaderFooterViewReuseIdentifier: "KAExitReasonHeader")
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.separatorColor = UIColor.clear
        tableView.bounces = true
        tableView.tableHeaderView = self.titleView
        tableView.backgroundColor = .white
        return tableView
    }()
    
    lazy var titleView: UIView = {
//        let label = UILabel()
//        label.numberOfLines = 0
//        label.font = UIFont.systemFont(ofSize: kscale(18), weight: .medium)
//        label.textColor = .black
//        label.text = "Please select the reason for not completing your info."
//        label.frame = CGRect(x: kscale(20), y: 0, width: var_screenWidth - kscale(40), height: kscale(50))
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: var_screenWidth, height: kscale(20)))
        view.backgroundColor = .white
//        view.addSubview(label)
        return view
    }()
    
    lazy var var_textView: KATextView = {
        let textView = KATextView()
        textView.contentPlaceHolder = "Please enter the reason for giving up."
        textView.contentText = ""
        textView.maxInputLength = 1000
        textView.countLabel.isHidden = true
        textView.inputTextComplete = { [weak self] content in
            self?.selectedRowModel.actualDeductionAmount = content
        }
        return textView
    }()
    
    private let var_tableFooter: KAExitBottomView = {
        let footerView = KAExitBottomView()
        footerView.backgroundColor = .white
        
        footerView.ka_addShadowAndCornerRadius(cornerRadius: kscale(8), shadowColor: .colorf2f2f5, shadowOpacity: 1, shadowOffset: CGSize(width: 0, height: 0), shadowRadius: kscale(8))
        
        return footerView
    }()
    
    @objc private func dismissPicker() {
        self.ka_dismiss()
        let btnInfo = KABtnInfo(eleId: "creditExit_remain", pageId: "creditUser_limit", clickTime: Date.ka_currentData())
        KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
    }
    
    @objc override func ka_show() {
        let data = KAPageInfo(eleId: "creditUser_limit", path: "\(KAInfoVC.self)")
        KAReport.ka_reportWith(type: .page, data: data.kj.JSONObject())
        
        alpha = 1.0
        let var_currentView = UIViewController.ka_current().view
        var_currentView?.addSubview(self)
        var_backgroundView.alpha = 0

        UIView.animate(withDuration: 0.25, delay: 0.0, animations: { [self] in
            var_backgroundView.alpha = 1
            var contentViewRect = var_shadowView.frame
            contentViewRect.origin.y = bounds.size.height - contentViewRect.size.height;
            var_shadowView.frame = contentViewRect;
        })
    }
   
    
    @objc private func clickDoneBtn() {
        guard !selectedSectionModel.templateDesignation.isEmpty else {
            self.makeToast("Please select a reason")
            return
        }
        if selectedSectionModel.secondaryLevelAccess.count > 0 && selectedRowModel.templateDesignation.isEmpty {
            self.makeToast("Please choose the reason for reject.")
            return
        }
        guard let model: KAExitReasonModel = self.dataArray.last else { return }
        if model.open && var_textView.contentText.isEmpty {
            self.makeToast("Please enter the reason for giving up.")
            return
        }
        
        let btnInfo = KABtnInfo(eleId: "creditStay_status", pageId: "creditUser_limit", clickTime: Date.ka_currentData())
        KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        
        let paramDic: [String : Any] = [
            "softwareUpdateVersions": KAUserManager.shared.user.softwareUpdateVersions,
            "interestRateone": selectedSectionModel.entityIdentifier,
            "secondaryLevelAccess":selectedRowModel.entityIdentifier,
            "actualDeductionAmount": selectedRowModel.actualDeductionAmount,
//            "operationGuidelines": Int(Date().timeIntervalSince1970),
            "presentationOrder": 0
        ]
        self.showLoading()
        loginProvider.request(.saveLeaveReason(paramDic)) { [self] result in
            self.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<[KAExitReasonModel]>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            ka_dismiss()
                            self.reasonSelected?("", true)
                        } else {
                            self.makeToast(message)
                        }
                    }
                }else {
                    self.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    @objc private func clickOnlineServiceBtn() {
        KAFlutterManager.showFlutterVC(route: "/onlineService", parameter: ["mobile" : KAUserManager.shared.user.notificationMessage])
    }
    
    @objc override func ka_doneAction(button: UIButton) {
        ka_dismiss()
        let btnInfo = KABtnInfo(eleId: "userAccess_control", pageId: "creditUser_limit", clickTime: Date.ka_currentData())
        KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
    }
    
    override func ka_initSubViews() {
        
        backTapEnable = true
        var_shadowView.frame = CGRectMake(0.0, bounds.size.height, bounds.size.width, kscale(520)+UIDevice.ka_safeBottom)
        var_backgroundView.effect = nil
        var_backgroundView.backgroundColor = UIColor.ka_hexColor(0x000000, alphaVaule: 0.66)
        var_backgroundView.alpha = 0.6
        var_contentView.frame = var_shadowView.bounds
        var_contentView.backgroundColor = .white
        //        var_backgroundView.backgroundColor = UIColor(0x000000, alphaVaule: 0.4)
        var_titleLabel.textColor = .black
        var_titleLabel.numberOfLines = 0
        var_titleLabel.font = UIFont.systemFont(ofSize: kscale(18), weight: .medium)
        var_titleLabel.text = "Please select the reason for not completing your info."
        
        var_line.backgroundColor = .clear
        var_closeButton.isHidden = true
        var_doneButton.setTitle("", for: .normal)
        var_doneButton.setImage(UIImage(named: "close_icon"), for: .normal)
        
        var_contentView.addSubview(self.var_tableView)
        var_contentView.addSubview(self.var_tableFooter)
        var_tableFooter.frame = CGRectMake(0, var_shadowView.height-kscale(100)-UIDevice.ka_safeBottom, var_screenWidth, UIDevice.ka_safeBottom+kscale(100))
        var_tableFooter.confirmButton.addTarget(self, action: #selector(dismissPicker), for: .touchUpInside)
        var_tableFooter.cancelButton.addTarget(self, action: #selector(clickDoneBtn), for: .touchUpInside)
        var_tableFooter.onlineServiceButton.addTarget(self, action: #selector(clickOnlineServiceBtn), for: .touchUpInside)
    }
    
    init(selectedBlock: ((String, Bool) -> Void)? = nil) {
        self.reasonSelected = selectedBlock
        super.init(frame: CGRect(x: 0, y: 0, width: var_screenWidth, height: var_screenHeight))
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension KAExitReasonPusher: UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        self.dataArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let model = self.dataArray[section];
        return model.open ? model.secondaryLevelAccess.count : 0;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model: KAExitReasonModel = self.dataArray[indexPath.section];
        let rowModel: KAExitReasonModel = model.secondaryLevelAccess[indexPath.row];
        let cell = KAExitReasonCell.ka_cell(for: tableView);
        cell.titleLabel.text = rowModel.templateDesignation;
        cell.isSelectedCell = rowModel.open;
        cell.selectionStyle = .none
        return cell;
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model: KAExitReasonModel = self.dataArray[indexPath.section];
        let secondModel: KAExitReasonModel = model.secondaryLevelAccess[indexPath.row];
        return CGFloat(secondModel.cellHeight)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var model: KAExitReasonModel = self.dataArray[section];
        let header: KAExitReasonHeader = tableView.dequeueReusableHeaderFooterView(withIdentifier: "KAExitReasonHeader") as! KAExitReasonHeader
//        header.contentView.backgroundColor = .blue
        header.titleLabel.text = model.templateDesignation;
        header.isSelectedHeader = model.open;
        header.tapAction = {
            if self.selectedSectionModel.templateDesignation == model.templateDesignation {
                return
            }
            model.open = !model.open
            self.selectedSectionModel.open = false
            self.selectedRowModel.open = false
            self.selectedSectionModel = model
            self.selectedRowModel = KAExitReasonModel()
            self.var_tableView.reloadData()
            if (section == self.dataArray.count-1) {
            }
        };
        return header;
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        let model: KAExitReasonModel = self.dataArray[section]
        return CGFloat(model.cellHeight)
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let model: KAExitReasonModel = self.dataArray[section]
        if (section == self.dataArray.count-1 && model.open) {
            return self.var_textView
        } else {
            return UIView()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        let model: KAExitReasonModel = self.dataArray[section]
        if (section == self.dataArray.count-1 && model.open) {
            return kscale(80)
        } else {
            return 0.01
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model: KAExitReasonModel = self.dataArray[indexPath.section]
        let rowModel: KAExitReasonModel = model.secondaryLevelAccess[indexPath.row]
        if self.selectedRowModel.templateDesignation == rowModel.templateDesignation {
            return
        }
        rowModel.open = !rowModel.open
        self.selectedRowModel.open = false
        self.selectedRowModel = rowModel
        self.var_tableView.reloadData()
    }
    
}
